package com.zhxh.nzpos.sell;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.zhxh.nzpos.Constants;
import com.zhxh.nzpos.R;
import com.zhxh.nzpos.dao.LocalInfoDao;
import com.zhxh.nzpos.dao.SelloutDao;
import com.zhxh.nzpos.dao.StockDao;
import com.zhxh.nzpos.model.LocalInfo;
import com.zhxh.nzpos.model.Sellout;
import com.zhxh.nzpos.serialport.PrintSerialPort;
import com.zhxh.nzpos.utils.ViewUtil;

/**
 * 商品销售的结算界面
 * 
 * @author wangzt
 * 
 */
public class SettleAccountActivity extends PrintSerialPort {

	private static final int SETTLE_SUCCESS = 1;
	private static final int SETTLE_FAIL = 2;

	private float total;// 总价
	private float youhui;// 优惠

	private float yingfukuan;// 应付款

	private int totalPoints; // 累计积分
	private float collected;

	private String noteId;

	private SelloutDao selloutDao;
	private StockDao stockDao;
	private String card;
	private LocalInfoDao dao;
	private String number;
	private LocalInfo localInfo;
	private String name = "";
	private String postid = "";
	private String phone = "";
	SendingThread mSendingThread;

	TextView discountMoneyView;
	private boolean isSave = false;

	private boolean isPrint = false;

	private ArrayList<Sellout> sellouts;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == SETTLE_SUCCESS) {
				ViewUtil.makeToast(getApplication(), "付款成功");

			} else {
				ViewUtil.makeToast(getApplication(), "付款失败");
			}
			ViewUtil.cancelProgressDialog();
		}

	};

	@SuppressWarnings("unchecked")
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sell_settle_account);
		Serializable extra = getIntent().getSerializableExtra(
				Constants.SELL_OUT_EXTRA);
		dao = new LocalInfoDao(this);
		initData();
		SharedPreferences sharedata = getSharedPreferences("PreferencesFile", 0);
		card = sharedata.getString("cardId", null);

		// SharedPreferences sharedata = getSharedPreferences("PreferencesFile",
		// 0);
		number = sharedata.getString("number", null);
		List<LocalInfo> locals = dao.getAll();
		if (locals.size() > 0)
			name = locals.get(0).getName();
		// name = dao.getAll()
		if (localInfo != null && localInfo.getName() != null) {
			name = localInfo.getName();
		}
		if (localInfo != null && localInfo.getPostId() != null) {
			postid = localInfo.getPostId();
		}
		if (localInfo != null && localInfo.getPhone() != null) {
			phone = localInfo.getPhone();
		}
		sellouts = (ArrayList<Sellout>) extra;

		selloutDao = new SelloutDao(getApplicationContext());
		stockDao = new StockDao(getApplicationContext());
		initViews();
	}

	private void initViews() {
		TextView cardView = (TextView) findViewById(R.id.member_card_tv);
		// card = getIntent().getStringExtra(Constants.MEMBER_CARD);
		noteId = getIntent().getStringExtra(Constants.SELL_NOTE_ID);

		if (card != null) {
			cardView.setText(getResources().getString(R.string.member_card)
					+ card);
		}
		// TextView cardid = (TextView) findViewById(R.id.member_card_id);
		// cardid.setText(card);

		//int thePoints = 0;
		for (Sellout sellout : sellouts) {
			total += sellout.getTotal();
		//	thePoints += sellout.getTotalPoints();
		}

		TextView totalView = (TextView) findViewById(R.id.total_account);
		totalView.setText("" + total);
		EditText discountView = (EditText) findViewById(R.id.goods_discount);
		discountView.addTextChangedListener(new TextWatcher()
		{
			public void afterTextChanged(Editable edt)
			{
				String temp = edt.toString();
				int posDot = temp.indexOf(".");
				if (posDot <= 0)
					return;
				if (temp.length() - posDot - 1 > 2)
				{
					edt.delete(posDot + 3, posDot + 4);
				}
			}
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
			}
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
			}

		});
		discountView.setText("0");
		discountMoneyView = (TextView) findViewById(R.id.money_after_discount);
		discountMoneyView.setText("" + total);

		final TextView zhaolingView = (TextView) findViewById(R.id.zhaoling);// 找零
		final EditText collectedET = (EditText) findViewById(R.id.collected_money);// 实收

		collectedET.addTextChangedListener(new TextWatcher()
		{
			public void afterTextChanged(Editable edt)
			{
				String temp = edt.toString();
				int posDot = temp.indexOf(".");
				if (posDot <= 0)
					return;
				if (temp.length() - posDot - 1 > 2)
				{
					edt.delete(posDot + 3, posDot + 4);
				}
			}
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
			}
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
			}

		});
		yingfukuan = total;
		discountView.setOnEditorActionListener(new OnEditorActionListener() {
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				// if (actionId == EditorInfo.IME_ACTION_DONE) {
				String cStr = ((EditText) v).getText().toString();

				try {
					youhui = Float.parseFloat(cStr);
					yingfukuan = total - youhui;
					if (youhui > total) {
						ViewUtil.makeToast(getApplication(), "请输入正确优惠价格");
						return false;
					}
					discountMoneyView.setText("" + (total - youhui));

					String shoukuan = collectedET.getText().toString();
					if (shoukuan != null && shoukuan.length() != 0) {
						collected = Float.parseFloat(shoukuan);

						zhaolingView.setText("" + (collected + youhui - total));
					}
				} catch (NumberFormatException e) {
					// e.printStackTrace();
				}
				// }
				return false;
			}
		});

		zhaolingView.setText("0");

		collectedET.setOnEditorActionListener(new OnEditorActionListener() {
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				// if (actionId == EditorInfo.IME_ACTION_DONE) {
				String cStr = ((EditText) v).getText().toString();
				try {
					collected = Float.parseFloat(cStr);
					if (total < collected) {
						float zl = collected - yingfukuan;
						zhaolingView.setText("" + zl);
					} else {
						ViewUtil.makeToast(getApplication(), "输入金额信息不正确");
					}
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
				// }
				return false;
			}
		});

		// final CheckBox shouldPrint = (CheckBox)
		// findViewById(R.id.no_print_doc_cb);

		Button okBtn = (Button) findViewById(R.id.deal_settle_account_btn);
		okBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				String shoukuan = collectedET.getText().toString();
				if (shoukuan.length() == 0) {
					ViewUtil.makeToast(getApplication(), "请输入收款金额");
					return;
				}
				String discountMoney = discountMoneyView.getText().toString();
				try {
					Float collected2 = Float.parseFloat(shoukuan);
					Float yingshou2 = Float.parseFloat(discountMoney);
					if (yingshou2 > collected2) {
						ViewUtil.makeToast(getApplication(), "收款金额不能小于应付款金额");
						return;
					}

				} catch (NumberFormatException e) {
					e.printStackTrace();
				}

				if (!isPrint) {
					print();
				}

				Intent i = new Intent();
				i.putExtra("success", "true");
				setResult(RESULT_OK, i);
				finish();
			}
		});
		Button cancelBtn = (Button) findViewById(R.id.deal_print_btn);
		cancelBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String shoukuan = collectedET.getText().toString();
				if (shoukuan.length() == 0) {
					ViewUtil.makeToast(getApplication(), "请输入收款金额");
					return;
				}
				// finish();
				print();
				isPrint = true;
			}
		});
	}

	private void sell() {
		// new Thread() {
		// public void run() {
		String orderid = selloutDao.sellAll(sellouts, totalPoints);
		System.out.println("printing1212/..........................orderid=."
				+ orderid);
		if (orderid != null) {
			noteId = orderid;
			// if (!shouldPrint.isChecked()) {
			handler.sendEmptyMessage(SETTLE_SUCCESS);
		} else {
			handler.sendEmptyMessage(SETTLE_FAIL);
		}
		// }
		// }.start();

	}

	private void print() {
		System.out.println("print/...........................");
		if (!isSave) {
			System.out.println("printing/...........................");
			sell();
			isSave = true;
		}
		if (collected >= total) {
			ViewUtil.showProgressDialog(SettleAccountActivity.this, "正在处理...");
			new Thread() {
				public void run() {
					System.out
							.println("printing2222/...........................");
					// if (!shouldPrint.isChecked()) {
					if (mSerialPort != null) {
						mSendingThread = new SendingThread();
						mSendingThread.start();
					} else {
						System.out
								.println("serial is null/...........................");
					}
				}

			}.start();
			ViewUtil.cancelProgressDialog();
		} else {
			ViewUtil.makeToast(getApplication(), "付款金额不能小于交易额!");
		}
	}

	/*
	 * 打印小票
	 */

	protected void onPrint(OutputStream mOutputStream) throws IOException {

		// TODO 按照格式补全打印信息
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm");

		mOutputStream.write("\r\n".getBytes());
		mOutputStream.write(("      大兴农资安全监管系统\r\n").getBytes("gbk"));
		String header = name;
		int len  = 16 - name.length();
		System.out.println("name==========="+name+"---");
		System.out.println("name.getBytes()===========");
		System.out.println("len==========="+len);
		if(len > 0) {
			int a = len /2;
			String tail = "";
			for(int m = 0 ; m < a; m++) {
				tail += "  ";
			}
			header = tail+header+tail;
		}
		mOutputStream.write((header+ "\r\n").getBytes("gbk"));
		String h1 = "流水号:" + noteId + "    机号:" + postid + " \r\n";
		String h2 = "收银员:" + number + "日期:"
				+ simpleDateFormat.format(new Date()) + "\r\n";

		mOutputStream.write(h1.getBytes("gbk"));
		mOutputStream.write(h2.getBytes("gbk"));
		mOutputStream.write("================================\r\n"
				.getBytes("gbk"));
		mOutputStream.write("商品名称     数量  单价  金额\r\n".getBytes("gbk"));
		/*
		 * mOutputStream.write("化肥         2    34   68.0\r\n".getBytes("gbk"));
		 * mOutputStream.write("化肥 份       2    34   68.0\r\n".getBytes("gbk"));
		 * mOutputStream.write("农药六六粉课   1    22   22.0\r\n".getBytes("gbk"));
		 */
		// String h3 = "农药六六粉课添加家（20%）";
		/*
		 * if(h3.getBytes().length > 16){ if(h3.length() <=8) { int j = 16 -
		 * h3.getBytes().length; while(j > 0){ h3 = h3.concat(" "); j--; }
		 * mOutputStream
		 * .write((h3+"12"+"     "+"23.3"+"    ""435.3\r\n").getBytes("gbk")); }
		 * else { String name1 = h3.substring(0,7); String name2 =
		 * h3.substring(8);
		 * mOutputStream.write((name1+sellout.getCount()+"     "
		 * +sellout.getPrice
		 * ()+"    "+sellout.getTotal()+"\r\n").getBytes("gbk"));
		 * mOutputStream.write((name2+"\r\n").getBytes("gbk")); } }
		 */

		int amount = 0;
		for (Sellout sellout : sellouts) {
			amount += sellout.getCount();
			String name = sellout.getGoodsName().trim();
			mOutputStream.write((name + "\r\n").getBytes("gbk"));
			mOutputStream.write(("              " + sellout.getCount() + "    "
					+ sellout.getPrice() + "  " + sellout.getTotal() + "\r\n")
					.getBytes("gbk"));
			/*
			 * if (name.length() <= 7 && name.getBytes().length <= 14) { int j =
			 * 14 - name.getBytes().length; while (j > 0) { name =
			 * name.concat(" "); j--; } mOutputStream .write((name +
			 * sellout.getCount() + "   " + sellout.getPrice() + "   " +
			 * sellout.getTotal() + "\r\n").getBytes("gbk")); } else { String
			 * name1 = name.substring(0, 7); String name2 = name.substring(7);
			 * mOutputStream .write((name1 + sellout.getCount() + "   " +
			 * sellout.getPrice() + "   " + sellout.getTotal() +
			 * "\r\n").getBytes("gbk")); mOutputStream.write((name2 +
			 * "\r\n").getBytes("gbk")); }
			 */

		}

		mOutputStream.write("===============================\r\n"
				.getBytes("gbk"));
		mOutputStream.write(("累计数量:" + amount + "   累计金额:" + total + "\r\n")
				.getBytes("gbk"));
		// mOutputStream.write(("累计金额:  " + total + "\r\n").getBytes("gbk"));

		if (youhui != 0) {
			mOutputStream.write(("减免金额:" + youhui + "\r\n").getBytes("gbk"));
		}
		mOutputStream
				.write(("收款:" + collected + "    找零:"
						+ (collected - total + youhui) + "       \r\n")
						.getBytes("gbk"));
		mOutputStream.write(("===============================\r\n")
				.getBytes("gbk"));
		mOutputStream.write(("    " + name + "欢迎您!   \r\n ").getBytes("gbk"));
		mOutputStream.write(("      订货电话:" + phone + "   \r\n ")
				.getBytes("gbk"));
		mOutputStream.write(("大兴区农委提醒您,请保留好小票!\r\n ").getBytes("gbk"));
		mOutputStream.write("\r\n\r\n".getBytes());

	}

	private class SendingThread extends Thread {
		@Override
		public void run() {
			// while (!isInterrupted()) {
			try {
				if (mOutputStream != null) {
					onPrint(mOutputStream);
					return;
				} else {
					return;
				}
			} catch (IOException e) {
				e.printStackTrace();
				return;
			}
			// }
		}
	}

	private void initData() {
		List<LocalInfo> locals = dao.getAll();
		if (locals.size() > 0)
			localInfo = locals.get(0);
	}

	@Override
	protected void onDataReceived(byte[] buffer, int size) {
		// TODO Auto-generated method stub

	}
}
